import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Alert,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
} from 'react-native';
import { observer } from 'mobx-react-lite';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { Ionicons } from '@expo/vector-icons';
import { RootStackParamList } from '@/route/Route';
import { useStore } from '@/route/Route';
import { Register } from '@/components';

type RegisterPageNavigationProp = StackNavigationProp<
  RootStackParamList,
  'Register'
>;

export const RegisterPage = observer(() => {
  const navigation = useNavigation<RegisterPageNavigationProp>();
  const { authStore } = useStore();
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const handleRegister = async () => {
    if (!username || !email || !password || !confirmPassword) {
      Alert.alert('提示', '请填写完整的注册信息');
      return;
    }

    if (password !== confirmPassword) {
      Alert.alert('提示', '两次输入的密码不一致');
      return;
    }

    if (password.length < 6) {
      Alert.alert('提示', '密码长度至少6位');
      return;
    }

    // Mock 注册逻辑
    try {
      // 模拟注册成功
      authStore.setUser({
        id: '1',
        email: email,
        username: username,
        avatar:
          'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=150&h=150&fit=crop&crop=face',
        createdAt: new Date().toISOString(),
      });

      Alert.alert('注册成功', '账户创建成功，欢迎使用 AutoCost！');
      // 注册成功后会自动跳转到主页面
    } catch (error) {
      Alert.alert('注册失败', '注册失败，请重试');
    }
  };

  const handleBackToLogin = () => {
    navigation.navigate('Login');
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <Register isLoading={authStore.isLoading} onRegister={handleRegister} />
    </KeyboardAvoidingView>
  );
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
});
